package fr.noe.amicaleloisirs.concours.servlets;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import fr.noe.amicaleloisirs.concours.constants.Constants;
import fr.noe.amicaleloisirs.concours.utils.FileUtil;
import fr.noe.amicaleloisirs.concours.utils.ServletUtil;

/**
 * Servlet implementation class SauveConcours
 */
public class SauveConcours extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private Logger logger = Logger.getLogger(SauveConcours.class);
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SauveConcours() {
        super();
        // TODO Auto-generated constructor stub
    }


	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		logger.debug("post receive");
		
		traiter(request, response, true);
	}
	
	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug("get receive");
		
		traiter(request, response, false);
	}
	
	private void traiter(HttpServletRequest request, HttpServletResponse response, boolean shouldContainXMLData) throws ServletException, IOException {
		String filename = request.getParameter("dateConcours");
		
		if (filename == null)
			response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Le nom du fichier n'est pas indiqué");
		else {
			String path = Constants.CONCOURS_URL_FILES + filename + ".xml";
			String old = Constants.CONCOURS_URL_FILES + filename + "_old.xml";
		
			if (FileUtil.fileExists(path)) {
				logger.debug("concours existant, faire une copie");
				
				if (FileUtil.fileExists(old))
					FileUtil.fileDelete(old);

				// copie temporaire à garder si echec de la sauvegarde pour le POST
				boolean moved = FileUtil.move(path, old);
				logger.debug("concours copié : " + moved);
			}
			
			if (shouldContainXMLData) {
				String doc = ServletUtil.getStringDataInRequest(request);
				boolean saveOk = FileUtil.write(path, doc);
				log("concours sauvé : " + saveOk);
				if (!saveOk) {
					// on restaure la copie
					FileUtil.move(old, path);
					response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Sauvegarde echouee");
				}
			}
			
		}
	}

}
